-- Parsec
-- Module 'scanner'
nild = {}

function set_color(c)
  theme.set("win.col.fg", c);
  theme.set("inv.col.link", c);
  theme.set("inv.col.fg", c);
end

function light(b)
  local c = "#ADADAD";
  local bgf = "bg";
  local cc = "theme/cursor.gif";
  _light = b;
  if b then
    c = "white";
    bgf = "white";
    cc = "theme/cursor2.gif";
  end
  set_color(c);
  --theme.set("scr.gfx.bg", "gfx/"..bgf..".jpg");
  --input.cursor = img(cc);
end

function light_(b)
  return function()
    light(b);
  end
end

function neuro()
  set_color("#ADADAD");
end

function exec(s,this)
  local f = assert(loadstring("return function(s)"..s.."; end"))();
  return f(this);
end

function exec_(s)
  return function(this)
    return exec(s,this);
  end
end

function apply(c,this)
  local f = assert(loadstring("return function(s) return ("..c.."); end"))();
  return f(this);
end

function apply_(c)
  return function(this)
    return apply(c,this);
  end
end

function cls()
  parser._lastdisp = '';
  parser._lastcmd = nil;
end

function redirect(s,w,t,act,obj)
  obj = nvl(obj,s);
  if type(obj) ~= "table" then
    obj = ref(obj);
  end
  local hdl = obj[act];
  if hdl == nilfn then
    hdl = parser.events[act];
    return rcall(hdl,parser,obj,w,t);
  elseif hdl ~= nil then
    return rcall(hdl,obj,w,t);
  end
  return true;
end

function redirect_(act,obj)
  return function(s, w, t)
    return redirect(s, w, t, act, obj);
  end
end

function direct_(act,obj,w,t)
  return function(s)
    return redirect(s, w, t, act, obj);
  end
end

function iif(c,x,y)
  if c then
    return x;
  else
    return y;
  end
end

function nvl(x,y)
  if x == nil then
    return y;
  else
    return x;
  end
end

function nilfn()
  return nil;
end

function rcall(o,s,w,t)
  if o == nil then
    return nil;
  elseif type(o) == "function" then
    return rcall(o(s,w,t), s,w,t);
  else
    return o;
  end
end

function notnil(o,nm)
  if o == nil then
    error("Error: "..nm.." is nil."..debug.traceback ());
  end
end

function raise(err)
  if err == nil then
    err = "";
  end
  error(err.."\n"..debug.traceback());
end